﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace SqliteLoader
{
    public partial class MainForm : Form
    {
		private SQLiteConnection _connection;

        public MainForm()
        {
            InitializeComponent();
        }

		private void ExitMenu_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void OpenDbMenu_Click(object sender, EventArgs e)
		{
			if (openDbDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				if (_connection == null || CloseDatabase())
					OpenDatabase(openDbDialog.FileName);
			}
		}

		private void OpenDatabase(string filename)
		{
			statusLabel.Text = "Opening Database...";
			var builder = new SQLiteConnectionStringBuilder();
			builder.DataSource = filename;
			builder.Pooling = true;
			builder.FailIfMissing = false;

			var connection = new SQLiteConnection(builder.ConnectionString);
			try
			{
				connection.Open();

				if (connection.State == ConnectionState.Open)
				{
					_connection = connection;
					CloseDbMenu.Visible = true;
					statusLabel.Text = "Database Open: " + filename;
				}
			}
			catch (SQLiteException ex)
			{
				HandleException(ex);
				statusLabel.Text = string.Empty;
			}
		}

		private bool CloseDatabase()
		{
			_connection.Close();
			_connection.Dispose();
			_connection = null;
			CloseDbMenu.Visible = false;
			statusLabel.Text = string.Empty;
			return true;
		}

		private void csvToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				if (ValidateConnection() && openDataFile.ShowDialog(this) == DialogResult.OK)
				{
					var wizard = new ImportWizard();
					wizard.Connection = _connection;
					wizard.Filenames = openDataFile.FileNames;

					wizard.GenerateDefaultMapping();

					wizard.Start();
				}
			}
			catch (Exception ex)
			{
				HandleException(ex);
			}
		}

		private void HandleException(Exception ex)
		{
			MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
		}



		private bool ValidateConnection()
		{
			if (_connection != null && _connection.State == ConnectionState.Open)
				return true;
			MessageBox.Show(this, "You need to open a database first.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
			return false;
		}

		private void CloseDbMenu_Click(object sender, EventArgs e)
		{
			CloseDatabase();
		}



    }
}
